pass
#####################################################################
# Product:      KnowledgeEngine (Plone Edition)
#
# File:         myknowledge_processor.py
#
# Copyright:    Copyright (c) 2004, Faulkner Technologies
#
# Author:       Brian Oliver
#
# Description:  A python script to control/handle requests from the
#               myknowledge.pt
#
#####################################################################

from Products.KnowledgeEngine.Utils.helpers import recordException

#get the request from the context... we will use it to find stuff!
request=context.REQUEST

form = request.form

return_url = form.get('came_from','') or '%s/%s' % (context.absolute_url(), 'myknowledge')

#get the sercurity, user provider and assessment storage services
securityService = context.knowledgeengine_securityservice
userProviderService = context.knowledgeengine_userproviderservice
assessmentStorageService = context.knowledgeengine_assessmentstorageservice
creditManagementService = context.knowledgeengine_creditmanagementservice

#get a list of the models
models = securityService.getModels()

#get the knowledge engine user
user = userProviderService.getUser(request["AUTHENTICATED_USER"].getId())

#go through all of the models to determine which one we are working with
for model in models:
        
    #get the AccessModel permission for the current model
    accessModelPermission = securityService.getEffectivePermission("AccessModel", model.getIdentity(), user.getIdentity())

    #can the user access the model?
    if accessModelPermission is not None and accessModelPermission.granted():
        
        #get the AccessPersonalRepository permission for the current model
        accessPersonalRepository = securityService.getEffectivePermission("AccessPersonalRepository", model.getIdentity(), user.getIdentity())

        #can the user access the personal repository
        if accessPersonalRepository is not None and accessPersonalRepository.granted():

            #was the create button pressed for the model?
            if request.form.has_key('btnCreateAssessment%s' % (model.getIdentity(),)):
                #------------------------------------#
                # CREATE ASSESSMENT (in personal repository)

                #get the name of the new assessment
                try:
                    assessmentName = request.form['txtName%s' % (model.getIdentity(),)]
                except KeyError:
                    # No assessment name specified
                    assessmentName = ""                    
                
                try: 
                    assessment = context.assessment_create( assessmentName, model, user )
                    
                    if model.getEnterOnCreate():
                        assessUrl = "%s/assess?assessmentIdentity=%s&exitURL=%s" % \
                            (model.absolute_url(), assessment.getIdentity(), return_url)
                            
                        return request.RESPONSE.redirect( assessUrl )
                    
                except Exception, e:    
                    failureMessage = str(e)                
                    request.set('portal_status_message', failureMessage)
                    recordException( context.error_log )
                    return context.myknowledge(context, request, error=failureMessage)
               
            #was the rename button pressed for the model?
            if request.form.has_key('btnRenameAssessments%s' % (model.getIdentity(),)):
                #------------------------------------#
                # RENAME ASSESSMENT(s) (in personal repository)

                #get permission
                renameAssessmentsInPersonalRepositoryPermission = securityService.getEffectivePermission("RenameAssessmentsInPersonalRepository", model.getIdentity(), user.getIdentity())

                #does the user have permission to rename assessment(s)?
                if renameAssessmentsInPersonalRepositoryPermission is not None and renameAssessmentsInPersonalRepositoryPermission.granted():

                    #build a list of the assessment to be renamed
                    assessmentIds = []
                    prefix = "txt%s" % (model.getIdentity(),)
                    for formKey in request.form.keys():
                        if prefix == formKey[0:len(prefix)]:
                            assessmentId = formKey[len(prefix):]
                            originalName = request.form['hid%s%s' % (model.getIdentity(), assessmentId)]
                            newName = request.form['txt%s%s' % (model.getIdentity(), assessmentId)]
                            if originalName != newName:                    
                                assessmentIds += [assessmentId]
                    assessments = [assessmentStorageService.loadAssessment(assessmentId, model) for assessmentId in assessmentIds]

                    #rename each of the assessments
                    for assessment in assessments:
                        #set the new name for the assessment                     
                        name = request.form['txt%s%s' % (model.getIdentity(), assessment.getIdentity())]
                        assessment.setName(name)

                        #now save the actual assessment
                        assessmentStorageService.saveAssessment(assessment)

                #user doesn't have permission to rename an assessment
                else:                
                    #notify the user that they don't have permission to create an assessment
                    failureMessage = "You do not have permission to rename assessments for %s.  Please contact your manager to request permission." % (model.getTitleOrId(),)
                    request.set('portal_status_message', failureMessage)
                    return context.myknowledge(context, request, error=failureMessage)

            #was the remove button pressed for the model?
            if request.form.has_key('btnRemoveAssessments%s' % (model.getIdentity(),)):
                #------------------------------------#
                # REMOVE ASSESSMENT (in personal repository)

                #get permission
                removeAssessmentsInPersonalRepositoryPermission = securityService.getEffectivePermission("RemoveAssessmentsInPersonalRepository", model.getIdentity(), user.getIdentity())

                #does the user have permission to remove assessment(s)?
                if removeAssessmentsInPersonalRepositoryPermission is not None and removeAssessmentsInPersonalRepositoryPermission.granted():

                    #build a list of the selected assessments
                    assessmentIds = []
                    prefix = "chkPersonal%s" % (model.getIdentity(),)
                    for formKey in request.form.keys():
                        if prefix == formKey[0:len(prefix)]:
                            assessmentId = formKey[len(prefix):]
                            assessmentIds += [assessmentId]
                    assessments = [assessmentStorageService.loadAssessment(assessmentId, model) for assessmentId in assessmentIds]

                    #remove each of the assessments 
                    for assessment in assessments:
                        #handle the 'onBeforeRemoveAssessmentFromPersonalRepository' event for the model
                        if model.isEventEnabled("onBeforeRemoveAssessmentFromPersonalRepository"):
                            model.getEnabledEvent("onBeforeRemoveAssessmentFromPersonalRepository").execute(assessment, user)

                        #handle the 'onBeforeRemoveAssessmentFromAnyRepository' event for the model
                        if model.isEventEnabled("onBeforeRemoveAssessmentFromAnyRepository"):
                            model.getEnabledEvent("onBeforeRemoveAssessmentFromAnyRepository").execute(assessment, user)

                        #now remove the actual assessment
                        assessmentStorageService.removeAssessmentFromRepository(assessment, user.getIdentity())

                    #TODO: redirect back to the 'myknowledge' page (with a success status message)

                #user doesn't have permission to remove an assessment
                else:                
                    #notify the user that they don't have permission to remove an assessment
                    failureMessage = "You do not have permission to remove personal assessments for %s.  Please contact your manager to request permission." % (model.getTitleOrId(),)
                    request.set('portal_status_message', failureMessage)
                    return context.myknowledge(context, request, error=failureMessage)


            # Was the create tag button pressed
            if request.form.has_key('btnCreateAssessmentTag%s' % (model.getIdentity(),)):
                if request.form.has_key('tagName%s' % (model.getIdentity(), )):
                    tag = request.form['tagName%s' % (model.getIdentity(), )]

                    #build a list of the selected assessments
                    assessmentIds = []
                    prefix = "chkPersonal%s" % (model.getIdentity(),)
                    for formKey in request.form.keys():
                        if prefix == formKey[0:len(prefix)]:
                            assessmentId = formKey[len(prefix):]
                            assessmentIds += [assessmentId]

                    assessments = [assessmentStorageService.loadAssessment(assessmentId, model) for assessmentId in assessmentIds]
                    for assessment in assessments:
                        assessment.setTags(tag, user)

            # Was the create tag button pressed
            if request.form.has_key('btnRemoveAssessmentTag%s' % (model.getIdentity(),)):
                if request.form.has_key('tagName%s' % (model.getIdentity(), )):
                    tag = request.form['tagName%s' % (model.getIdentity(), )]

                    #build a list of the selected assessments
                    assessmentIds = []
                    prefix = "chkPersonal%s" % (model.getIdentity(),)
                    for formKey in request.form.keys():
                        if prefix == formKey[0:len(prefix)]:
                            assessmentId = formKey[len(prefix):]
                            assessmentIds += [assessmentId]

                    assessments = [assessmentStorageService.loadAssessment(assessmentId, model) for assessmentId in assessmentIds]
                    for assessment in assessments:
                        assessment.removeTags(tag, user)


            #was the perform assessment actions button pressed for the model?
            # HACK- Copy-Pasted code, needs cleaning up.
            if request.form.has_key('btnPerformAssessmentActions%s' % (model.getIdentity(),)):
                #------------------------------------#
                # PERFORM ASSESSMENT ACTIONS (in personal repository)

                #build a list of the assessment and action identities
                assessmentsActions = {}
                prefix = "cmbAssessmentAction%s" % (model.getIdentity(),)
                for formKey in request.form.keys():
                    if prefix == formKey[0:len(prefix)]:
                        assessmentId = formKey[len(prefix):]
                        actionId = request.form.get(formKey)
                        
                        #only add assessment with selected actions
                        if len(actionId) > 0:
                            assessmentsActions[assessmentId] = actionId
                
                #execute the actions for each of the assessments
                for assessmentId in assessmentsActions.keys():
                    #find the assessment action 
                    assessmentActionId = assessmentsActions[assessmentId]
                    assessmentAction = model.getGenericObject(assessmentActionId)

                    #get the permission for the current report
                    actionPermission = securityService.getEffectivePermission("ExecuteAssessmentAction", assessmentAction.getIdentity(), user.getIdentity())
    
                    #does the user have permission to execute the action?
                    if actionPermission is not None and actionPermission.granted():             
                        #load the assessment
                        assessment = assessmentStorageService.loadAssessment(assessmentId, model)
                        
                        #perform the action using the assessment
                        assessmentAction.execute(assessment, user)
                        
                        #save the assessment just in case it's changed
                        assessmentStorageService.saveAssessment(assessment)
             
                # HACK - Quick and dirty method for the actions to signal a redirect in this script
                if context.REQUEST.get('_action_redirect', False):
                    return_url = context.REQUEST['_action_redirect']
                
        #the user doesn't have access to their personal repository
        else:
            #we ignore requests if the user doesn't have access.
            pass
                
        #------------------------------------#
        #go through all of the repositories to determine if we need to process a specific repository action
        for repository in model.getRepositories():
        
            #get the AccessRepository permission for the current repository
            accessRepository = securityService.getEffectivePermission("AccessRepository", repository.getIdentity(), user.getIdentity())

            #can the user access the repository
            if accessRepository is not None and accessRepository.granted():

                #was the rename button pressed for the repository?
                if request.form.has_key('btnRenameAssessments%s' % (repository.getIdentity(), )):
                    #------------------------------------#
                    # RENAME ASSESSMENT(s) (in repository)

                    #get permission
                    renameRepositoryAssessmentsPermission = securityService.getEffectivePermission("RenameRepositoryAssessments", repository.getIdentity(), user.getIdentity())

                    #does the user have permission to rename assessment(s)?
                    if renameRepositoryAssessmentsPermission is not None and renameRepositoryAssessmentsPermission.granted():

                        #build a list of the assessment to be renamed
                        assessmentIds = []
                        prefix = "txt%s" % (repository.getIdentity(),)
                        for formKey in request.form.keys():
                            if prefix == formKey[0:len(prefix)]:
                                assessmentId = formKey[len(prefix):]
                                originalName = request.form['hid%s%s' % (repository.getIdentity(), assessmentId)]
                                newName = request.form['txt%s%s' % (repository.getIdentity(), assessmentId)]
                                if originalName != newName:                    
                                    assessmentIds += [assessmentId]
                        assessments = [assessmentStorageService.loadAssessment(assessmentId, repository.getModel()) for assessmentId in assessmentIds]

                        #rename each of the assessments
                        for assessment in assessments:
                            #set the new name for the assessment
                            assessment.setName(request.form['txt%s%s' % (repository.getIdentity(), assessment.getIdentity())])

                            #now save the actual assessment
                            assessmentStorageService.saveAssessment(assessment)

                    #user doesn't have permission to rename an assessment
                    else:                
                        #notify the user that they don't have permission to create an assessment
                        failureMessage = "You do not have permission to rename assessments for %s.  Please contact your manager to request permission." % (repository.getTitleOrId(),)
                        request.set('portal_status_message', failureMessage)
                        return context.myknowledge(context, request, error=failureMessage)

                #was the remove button pressed for the repository?
                if request.form.has_key('btnRemoveAssessments%s' % (repository.getIdentity(),)):
                    #------------------------------------#
                    # REMOVE ASSESSMENT (in repository)

                    #get permission
                    removeRepositoryAssessmentsPermission = securityService.getEffectivePermission("RemoveRepositoryAssessments", repository.getIdentity(), user.getIdentity())

                    #does the user have permission to remove assessment(s)?
                    if removeRepositoryAssessmentsPermission is not None and removeRepositoryAssessmentsPermission.granted():

                        #build a list of the selected assessments
                        assessmentIds = []
                        prefix = "chkRepository%s" % (repository.getIdentity(),)
                        for formKey in request.form.keys():
                            if prefix == formKey[0:len(prefix)]:
                                assessmentId = formKey[len(prefix):]
                                assessmentIds += [assessmentId]
                        assessments = [assessmentStorageService.loadAssessment(assessmentId, repository.getModel()) for assessmentId in assessmentIds]

                        #remove each of the assessments 
                        for assessment in assessments:
                            #handle the 'onBeforeRemoveAssessmentFromRepository' event for the model
                            if repository.isEventEnabled("onBeforeRemoveAssessmentFromRepository"):
                                repository.getEnabledEvent("onBeforeRemoveAssessmentFromRepository").execute(assessment, user)

                            #handle the 'onBeforeRemoveAssessmentFromAnyRepository' event for the model
                            if model.isEventEnabled("onBeforeRemoveAssessmentFromAnyRepository"):
                                model.getEnabledEvent("onBeforeRemoveAssessmentFromAnyRepository").execute(assessment, user)

                            #now remove the actual assessment
                            assessmentStorageService.removeAssessmentFromRepository(assessment, repository.getIdentity())

                        #TODO: redirect back to the 'myknowledge' page (with a success status message)

                    #user doesn't have permission to remove an assessment
                    else:                
                        #notify the user that they don't have permission to remove an assessment
                        failureMessage = "You do not have permission to remove assessments from %s.  Please contact your manager to request permission." % (repository.getTitleOrId(),)
                        request.set('portal_status_message', failureMessage)
                        return context.myknowledge(context, request, error=failureMessage)


                # Was the create tag button pressed
                if request.form.has_key('btnCreateAssessmentTag%s' % (repository.getIdentity(),)):
                    if request.form.has_key('tagName%s' % (repository.getIdentity(), )):
                        tag = request.form['tagName%s' % (repository.getIdentity(), )]

                        #build a list of the selected assessments
                        assessmentIds = []
                        prefix = "chkRepository%s" % (repository.getIdentity(),)
                        for formKey in request.form.keys():
                            if prefix == formKey[0:len(prefix)]:
                                assessmentId = formKey[len(prefix):]
                                assessmentIds += [assessmentId]

                        assessments = [assessmentStorageService.loadAssessment(assessmentId, repository.getModel()) for assessmentId in assessmentIds]
                        for assessment in assessments:
                            assessment.setTags(tag, user)

                # Was the create tag button pressed
                if request.form.has_key('btnRemoveAssessmentTag%s' % (repository.getIdentity(),)):
                    if request.form.has_key('tagName%s' % (repository.getIdentity(), )):
                        tag = request.form['tagName%s' % (repository.getIdentity(), )]

                        #build a list of the selected assessments
                        assessmentIds = []
                        prefix = "chkRepository%s" % (repository.getIdentity(),)
                        for formKey in request.form.keys():
                            if prefix == formKey[0:len(prefix)]:
                                assessmentId = formKey[len(prefix):]
                                assessmentIds += [assessmentId]

                        assessments = [assessmentStorageService.loadAssessment(assessmentId, repository.getModel()) for assessmentId in assessmentIds]
                        for assessment in assessments:
                            assessment.removeTags(tag, user)


                #was the perform assessment actions button pressed for the repository?
                if request.form.has_key('btnPerformAssessmentActions%s' % (repository.getIdentity(),)):
                    #------------------------------------#
                    # PERFORM ASSESSMENT ACTIONS (in repository)
    
                    #build a list of the assessment and action identities
                    assessmentsActions = {}
                    prefix = "cmbAssessmentAction%s" % (repository.getIdentity(),)
                    for formKey in request.form.keys():
                        if prefix == formKey[0:len(prefix)]:
                            assessmentId = formKey[len(prefix):]
                            actionId = request.form.get(formKey)
                            
                            #only add assessment with selected actions
                            if len(actionId) > 0:
                                assessmentsActions[assessmentId] = actionId
                  
                    
                    #execute the actions for each of the assessments
                    for assessmentId in assessmentsActions.keys():
                        #find the assessment action 
                        assessmentActionId = assessmentsActions[assessmentId]
                        assessmentAction = model.getGenericObject(assessmentActionId)
    
                        #get the permission for the current report
                        actionPermission = securityService.getEffectivePermission("ExecuteAssessmentAction", assessmentAction.getIdentity(), user.getIdentity())
                                        
                        #does the user have permission to execute the action?
                        if actionPermission is not None and actionPermission.granted():             
                            #load the assessment
                            assessment = assessmentStorageService.loadAssessment(assessmentId, model)
                            
                            #perform the action using the assessment
                            assessmentAction.execute(assessment, user)
                            
                            #save the assessment just in case it's changed
                            assessmentStorageService.saveAssessment(assessment)
                            
                            
                    if context.REQUEST.get('_action_redirect', False):
                        return_url = context.REQUEST['_action_redirect']

            #the user doesn't have access to the current repository                                 
            else:
                #we ignore requests if the user doesn't have access.
                pass
                
    #the user doesn't have access to the model
    else:
        #we ignore requests if the user doesn't have access.
        pass
                
#------------------------------------#
#redirect back to the myknowledge page




return request.RESPONSE.redirect(return_url)
